//
//  ZBDownloadManager.m
//  PaoPao
//
//  Created by xzb on 2018/4/21.
//  Copyright © 2018年 paopao. All rights reserved.
//

#import "ZBDownloadManager.h"
#import <SDWebImage/SDWebImageManager.h>

@implementation ZBDownloadManager

+ (instancetype)instance
{
    static dispatch_once_t oncePredicate;
    static id instance;
    dispatch_once(&oncePredicate, ^{
        instance = [[self alloc] init];
    });
    return instance;
};

+ (void)ZB_downloadImageWithURL:(NSURL *)url completed:(ZBWebImageZBCompletionBlock)completedBlock
{
    [self ZB_downloadImageWithURL:url progress:nil completed:completedBlock];
}

+ (void)ZB_downloadImageWithURL:(NSURL *)url progress:(ZBWebImageDownloaderProgressBlock)progressBlock completed:(ZBWebImageZBCompletionBlock)completedBlock
{
    [SDWebImageManager.sharedManager loadImageWithURL:url options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
        if (progressBlock) {
            progressBlock(receivedSize, expectedSize);
        }
        
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (completedBlock) {
            ZBImageCacheType zbCacheType = (int)cacheType;
            completedBlock(image, error, zbCacheType, imageURL);
        }
    }];
}

+ (void)ZB_queryCacheForURL:(NSURL *)url completed:(ZBWebImageQueryCompletedBlock)completedBlock
{
    [[SDImageCache sharedImageCache] queryCacheOperationForKey:[[SDWebImageManager sharedManager] cacheKeyForURL:url] done:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
        if (completedBlock) {
            ZBImageCacheType zbCacheType = (int)cacheType;
            completedBlock(image,zbCacheType);
        }
    }];
}

+ (NSString *)filePathForURL:(NSURL *)url
{
    return [[SDImageCache sharedImageCache] defaultCachePathForKey:[[SDWebImageManager sharedManager] cacheKeyForURL:url]];
}

+(void)ZB_clear
{
    [self ZB_clearAllOnCompletion:nil];
}

+ (void)ZB_clearAllOnCompletion:(void (^)(void))completion
{
    [[SDImageCache sharedImageCache] clearMemory];
    [self ZB_clearDiskOnCompletion:completion];
}

+ (void)ZB_clearDiskOnCompletion:(void (^)(void))completion
{
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        if (completion) {
            completion();
        }
    }];
}
@end
